<template>
  <div class="search-container">
    <!-- 顶部导航栏 -->
    <header class="search-header">
      <div class="back-button" @click="goBack">
        <i class="fa fa-arrow-left iconfont">&#xe60b;</i>
        <!-- <i class="iconfont icon-back" @click="goBack">&#xe60b;</i> -->
      </div>
      <div class="search-input-wrapper">
        <i class="fa fa-search search-icon"></i>
        <input 
          v-model="searchQuery" 
          type="text" 
          :placeholder="currentPlaceholder" 
          class="search-input" 
          @keyup.enter="handleSearch"
          @focus="stopCarousel"
          @blur="startCarousel"
        >
        
        <button class="search-button" @click="searchSearch">搜索</button>
      </div>
    </header>
    
    <!-- 搜索内容区域 -->
    <main class="search-content">
      <!-- 历史搜索 -->
      <div class="search-section history-section" v-if="searchHistory.length > 0">
        <div class="section-header">
          <h3>历史搜索</h3>
          <button class="clear-button" @click="clearHistory">
            <i class="fa fa-trash"></i> 清空
          </button>
        </div>
        <div class="tag-container">
          <span 
            v-for="(item, index) in searchHistory" 
            :key="index" 
            class="search-tag"
            @click="fillSearchQuery(item)"
          >
            <i class="fa fa-history history-icon"></i>
            {{ item }}
            <i 
              class="fa fa-times delete-icon" 
              @click.stop="removeHistory(index)"
            ></i>
          </span>
        </div>
      </div>

      <!-- 搜索发现 -->
      <div class="search-section discovery-section">
        <div class="section-header">
          <h3>搜索发现</h3>
          <button 
            class="refresh-button" 
            @click="refreshDiscovery"
            :disabled="isRefreshing"
          >
            <i class="fa fa-refresh" :class="{ 'fa-spin': isRefreshing }"></i>
            <span v-if="!isRefreshing">换一批</span>
            <span v-else>加载中...</span>
          </button>
        </div>
        <div class="discovery-tags">
          <span 
            v-for="(item, index) in searchDiscovery" 
            :key="index" 
            class="discovery-tag"
            :class="{ 'hot-tag': item.badge === '热门' }"
            @click="fillSearchQuery(item.text)"
          >
            {{ item.text }}
            <span v-if="item.badge === '热门'" class="badge">{{ item.badge }}</span>
          </span>
        </div>
      </div>

      <!-- 趋势播报 -->
      <div class="search-section trend-section">
        <h3 class="trend-title">趋势播报</h3>
        <ul class="trend-list">
          <li 
            v-for="(item, index) in allTrends" 
            :key="index" 
            class="trend-item"
            @click="fillSearchQuery(item.title)"
          >
            <div class="trend-item-left">
              <div class="trend-rank-wrapper">
                <span class="trend-rank" :class="{ 'top-three': index < 3 }">{{ index + 1 }}</span>
                <img :src="item.image" alt="商品图片" class="trend-image" />
              </div>
            </div>
            <div class="trend-item-content">
              <div class="trend-item-title">
                {{ item.title }}
                <span v-if="item.badge" class="badge">{{ item.badge }}</span>
              </div>
              <div class="trend-item-subtitle">{{ item.subtitle }}</div>
            </div>
            <div class="trend-item-value">
              <span class="trend-value">趋势值{{ item.value }}</span>
            </div>
          </li>
        </ul>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';

// 获取路由实例
const router = useRouter();

// 搜索相关数据
const searchQuery = ref('');
const searchHistory = ref([]);
const isRefreshing = ref(false);
const refreshCount = ref(0);

// 新增轮播相关数据
const carouselIndex = ref(0);
const carouselTimer = ref(null);
const carouselInterval = ref(3000); // 3秒切换一次
const placeholderCarousel = ref([
  '窑鸡王',
  '乳香芝士奶角',
  '炒米粉',
  '姜爆鸭',
  '麻辣小龙虾',
  '椰青西瓜爆爆珠'
]);
const currentPlaceholder = ref(placeholderCarousel.value[0]);

// 搜索发现数据池
const discoveryPool = [
  [
    { text: '特惠神券包', badge: '热门' },
    { text: '干锅', badge: '' },
    { text: '炒菜', badge: '' },
    { text: '盐焗鸡', badge: '' },
    { text: '蜜雪冰城', badge: '' },
    { text: '奶茶', badge: '' },
    { text: '现包手工饺子', badge: '' },
    { text: '曹氏鸭脖', badge: '' },
    { text: '手撕鸡', badge: '' },
    { text: '跷脚牛肉', badge: '' },
    { text: '卤菜', badge: '' },
    { text: '凉拌菜', badge: '' },
    { text: '窑鸡', badge: '' },
    { text: '冒菜', badge: '' },
    { text: '酸菜鱼', badge: '' },
    { text: '烤肉', badge: '' },
    { text: '火锅', badge: '' },
    { text: '寿司', badge: '' },
    { text: '披萨', badge: '' },
    { text: '汉堡', badge: '' }
  ],
  [
    { text: '特惠神券包', badge: '热门' },
    { text: '意大利面', badge: '' },
    { text: '冰淇淋', badge: '热销' },
    { text: '鸡尾酒', badge: '' },
    { text: '薯条', badge: '' },
    { text: '甜甜圈', badge: '' },
    { text: '饼干', badge: '' },
    { text: '巧克力', badge: '' },
    { text: '抹茶拿铁', badge: '' },
    { text: '咖啡', badge: '' },
    { text: '甜点', badge: '' },
    { text: '水果', badge: '' },
    { text: '沙拉', badge: '' },
    { text: '快餐', badge: '' },
    { text: '下午茶', badge: '' },
    { text: '早餐', badge: '' },
    { text: '夜宵', badge: '' },
    { text: '外卖', badge: '' },
    { text: '家常菜', badge: '' },
    { text: '川菜', badge: '' }
  ],
  [
    { text: '特惠神券包', badge: '热门' },
    { text: '粤菜', badge: '' },
    { text: '湘菜', badge: '' },
    { text: '日料', badge: '' },
    { text: '韩料', badge: '' },
    { text: '泰餐', badge: '' },
    { text: '西餐', badge: '' },
    { text: '东北菜', badge: '' },
    { text: '西北菜', badge: '' },
    { text: '云南菜', badge: '' },
    { text: '贵州菜', badge: '' },
    { text: '新疆菜', badge: '' },
    { text: '清真菜', badge: '' },
    { text: '素食', badge: '' },
    { text: '健康餐', badge: '' },
    { text: '儿童餐', badge: '' },
    { text: '老人餐', badge: '' },
    { text: '孕妇餐', badge: '' },
    { text: '减肥餐', badge: '' },
    { text: '健身餐', badge: '' }
  ]
];

// 当前显示的搜索发现
const searchDiscovery = ref(discoveryPool[0]);

// 趋势播报数据 - 使用更匹配的食品图片
const allTrends = ref([
  { 
    title: '乳香芝士奶角', 
    subtitle: '好利来新品 | 细腻轻盈，入口即化的芝士风味', 
    value: '99.0万', 
    badge: '爆', 
    image:'https://ts3.tc.mm.bing.net/th/id/OIP-C._Pzd50dYPLzKQIecl_vsCgHaLA?w=205&h=304&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '炒米粉', 
    subtitle: '经典粤式小吃 | 弹牙米粉搭配秘制酱料，香气四溢', 
    value: '75.9万', 
    badge: '热', 
    image: 'https://ts2.tc.mm.bing.net/th/id/OIP-C.NnbnzHvKXCkSIdlVRQ9GagHaE9?w=305&h=204&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '姜爆鸭', 
    subtitle: '川渝名菜 | 鸭肉鲜嫩，姜片提香，麻辣过瘾', 
    value: '59.0万', 
    badge: '', 
    image: 'https://ts4.tc.mm.bing.net/th/id/OIP-C.kpo2QDqKueRbenddiciRCAHaE6?w=306&h=203&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '麻辣小龙虾', 
    subtitle: '夏季必备 | 鲜嫩虾肉裹满麻辣汤汁，吮指回味', 
    value: '58.6万', 
    badge: '热', 
    image: 'https://ts4.tc.mm.bing.net/th/id/OIP-C.iW0y1iAGnfjM64ryX98zywHaE7?w=306&h=204&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '椰青西瓜爆爆珠', 
    subtitle: '茶百道新品 | 清甜椰青搭配爽口西瓜爆珠，夏日清凉', 
    value: '58.5万', 
    badge: '新', 
    image: 'https://ts3.tc.mm.bing.net/th/id/OIP-C.GmHNOUESwfbwKN_1NU4p2wHaJ4?w=216&h=288&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '鸡米花', 
    subtitle: '酥脆外皮包裹嫩滑鸡肉，一口接一口停不下来', 
    value: '58.5万', 
    badge: '热', 
    image: 'https://ts2.tc.mm.bing.net/th/id/OIP-C.-nKEEV8kdi1aKTJofb8-hAHaFL?w=298&h=209&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '螺蛳粉', 
    subtitle: '广西特色 | 酸辣汤底搭配弹牙米粉，正宗柳州风味', 
    value: '58.4万', 
    badge: '', 
    image: 'https://ts2.tc.mm.bing.net/th/id/OIP-C.bzqJLeWW2RQv7BHDvOgAUgHaHS?w=251&h=248&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '叫花鸡', 
    subtitle: '传统名菜 | 荷叶包裹，泥烤工艺，肉质鲜嫩多汁', 
    value: '55.8万', 
    badge: '', 
    image: 'https://ts2.tc.mm.bing.net/th/id/OIP-C.ahZb2q8y-2nXIij4xda17gHaFR?w=296&h=211&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '生腌', 
    subtitle: '潮汕风味 | 鲜虾、螃蟹等海鲜用秘制酱料腌制，原汁原味', 
    value: '52.9万', 
    badge: '', 
    image: 'https://ts3.tc.mm.bing.net/th/id/OIP-C.21gREZNfd-5tD0FhAp5JmwHaFj?w=288&h=216&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  },
  { 
    title: '炒方便面', 
    subtitle: '简单美味 | 方便面翻炒后更有嚼劲，搭配蔬菜鸡蛋更营养', 
    value: '50.1万', 
    badge: '', 
    image: 'https://ts2.tc.mm.bing.net/th/id/OIP-C.wN4XILQteA3uRdN0FCP7TwHaI3?w=228&h=273&c=8&rs=1&qlt=90&o=6&dpr=2.8&pid=3.1&rm=2'
  }
]);

// 生命周期钩子
onMounted(() => {
  // 从本地存储加载历史记录
  const savedHistory = localStorage.getItem('searchHistory');
  if (savedHistory) {
    searchHistory.value = JSON.parse(savedHistory);
  }
  
  // 启动占位符轮播
  startCarousel();
  
  // 监听搜索框变化，输入时暂停轮播
  watch(searchQuery, (newVal) => {
    if (newVal) {
      stopCarousel();
    } else {
      startCarousel();
    }
  });
});

onUnmounted(() => {
  // 清理定时器
  stopCarousel();
});

// 启动轮播
const startCarousel = () => {
  stopCarousel();
  carouselTimer.value = setInterval(() => {
    carouselIndex.value = (carouselIndex.value + 1) % placeholderCarousel.value.length;
    currentPlaceholder.value = placeholderCarousel.value[carouselIndex.value];
  }, carouselInterval.value);
};

// 停止轮播
const stopCarousel = () => {
  if (carouselTimer.value) {
    clearInterval(carouselTimer.value);
    carouselTimer.value = null;
  }
};

// 执行搜索
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    // 添加到历史记录
    addToHistory(searchQuery.value.trim());
    // 执行搜索操作
    console.log('执行搜索:', searchQuery.value);
  }
};

// 添加到历史记录
const addToHistory = (query) => {
  // 移除重复项
  const index = searchHistory.value.indexOf(query);
  if (index !== -1) {
    searchHistory.value.splice(index, 1);
  }
  // 添加到开头
  searchHistory.value.unshift(query);
  // 限制历史记录数量
  if (searchHistory.value.length > 10) {
    searchHistory.value.pop();
  }
  // 保存到本地存储
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
};

// 移除单条历史记录
const removeHistory = (index) => {
  searchHistory.value.splice(index, 1);
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
};

// 清除所有历史记录
const clearHistory = () => {
  searchHistory.value = [];
  localStorage.removeItem('searchHistory');
};

// 填充搜索框
const fillSearchQuery = (text) => {
  searchQuery.value = text;
  stopCarousel(); // 填充时暂停轮播
};

// 搜索
const searchSearch = () => {
  if (!searchQuery.value.trim()) {
    searchQuery.value = currentPlaceholder.value; // 如果搜索框为空，使用当前轮播的占位符
  }
  // 添加到历史记录
  addToHistory(searchQuery.value.trim());
  // 跳转下一页
  router.push({
    name: 'Sort', 

  });
};

// 返回上一页
const goBack = () => {
  stopCarousel(); // 返回时停止轮播
  router.back();
};

// 刷新搜索发现
const refreshDiscovery = async () => {
  if (isRefreshing.value) return;
  
  isRefreshing.value = true;
  
  try {
    // 模拟加载延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 循环使用数据池中的数据
    refreshCount.value = (refreshCount.value + 1) % discoveryPool.length;
    searchDiscovery.value = discoveryPool[refreshCount.value];
    
  } finally {
    isRefreshing.value = false;
  }
};
</script>

<style scoped>
/* 基础样式 */
.search-container {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  background-color: #f8f8f8;
  min-height: 100vh;
  font-size: 20px;
}

/* 头部样式 */
.search-header {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
  padding: 10px;
  color: #333;
  font-size: 24px;
  background-color: #f5f5f5;
}

.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  border-radius: 30px;
  padding: 0 15px;
  margin: 0 15px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); /* 添加轻微阴影 */
}

.search-icon {
  color: #999;
  margin-right: 10px;
}

.search-input {
  flex: 1;
  border: none;
  background-color: #ffffff;
  height: 40px;
  outline: none;
  font-size: 20px;
  /* 占位符样式优化 */
  &::placeholder {
    color: #a0a0a0;
    transition: color 0.3s;
  }
  
  &:focus::placeholder {
    color: #c0c0c0;
  }
}

.search-button {
  border: none;
  background-color: #f5f5f5;
  color: black;
  background: none;
  font-size: 25px;
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: 500;
  line-height: 35px;
}
.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}
/* 在 input 和 button 之间插竖线 */
.search-button::before {
  content: "";
  display: inline-block;
  width: 1px;
  height: 27px; /* 竖线高度，可调整 */
  background-color: #999;
  margin-right: 20px; /* 跟按钮隔开 */
  margin-top: 10px;
  
}

.search-section {
  background-color: white;
  padding: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.clear-button {
  border: none;
  background-color: #ffffff;
  color: #999;
  font-size: 18px;
  display: flex;
  align-items: center;
}

/* 历史搜索样式 */
.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.search-tag {
  background-color: #f2f2f2;
  border-radius: 20px;
  padding: 10px 16px;
  padding-right: 30px;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  position: relative;
  cursor: pointer;
  transition: all 0.2s;
}

.search-tag:hover {
  background-color: #eaeaea;
}

.history-icon {
  color: #999;
  margin-right: 6px;
}

.delete-icon {
  color: #999;
  font-size: 14px;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0;
  transition: opacity 0.2s;
}

.search-tag:hover .delete-icon {
  opacity: 1;
}

/* 搜索发现样式 */
.refresh-button {
  border: none;
  background-color: #ffffff;
  color: #878787;
  font-size: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.refresh-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.discovery-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.discovery-tag {
  background-color: #f8f8f8;
  border-radius: 30px;
  padding: 12px 16px;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}

.discovery-tag:hover {
  background-color: #f2f2f2;
  transform: translateY(-2px);
}

.hot-tag {
  background-color: #fff2e8;
  color: #ff4500;
}

.hot-tag:hover {
  background-color: #ffe8d9;
}

.badge {
  font-size: 14px;
  padding: 3px 6px;
  border-radius: 4px;
  margin-left: 8px;
  font-weight: 500;
}

.badge.热门 {
  background-color: #ff4500;
  color: white;
}

/* 趋势播报样式 */
.trend-title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin-bottom: 24px;
  position: relative;
  display: inline-block;
}

.trend-title::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 70%;
  height: 4px;
  background: linear-gradient(90deg, #ff4500, #ff7d00);
  border-radius: 4px;
}

.trend-list {
  list-style: none;
  padding: 0;
}

.trend-item {
  display: flex;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f5f5f5;
  transition: transform 0.2s ease;
}

.trend-item:last-child {
  border-bottom: none;
}

.trend-item-left {
  position: relative;
  margin-right: 20px;
}

.trend-rank-wrapper {
  position: relative;
}

.trend-image {
  width: 120px; 
  height: 120px;
  border-radius: 12px;
  object-fit: cover;
  box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.trend-rank {
  position: absolute;
  top: -12px;   /* 调整位置 */
  background-color: rgb(190, 150, 118);
  width: 40px;  
  height: 40px; 
  line-height: 40px;
  text-align: center;
  font-size: 24px;
  font-weight: 700;
  color: white;
  box-shadow: 0 3px 8px rgba(0,0,0,0.15);
  z-index: 10;
  border-radius:12px 0 12px 0;
  left:0px;
  top:0;
}

.top-three {
  /* background: linear-gradient(135deg, #ff4500, #ff7d00); */
  background-color: rgb(254, 65, 33);
  color: white;
  box-shadow: 0 4px 12px rgba(255, 69, 0, 0.4);
  border-radius:13px 0 13px 0;
  left:0px;
  top:0;
}

.trend-item-content {
  flex: 1;
  margin-right: 20px;
}

.trend-item-title {
  font-size: 26px;
  color: #333;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  font-weight: 600;
}

.trend-item-subtitle {
  font-size: 20px;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  width:300px;
}

.trend-item-value {
  display: flex;
  align-items: center;
}
.trend-value {
  font-size: 22px;
  color: rgb(138,138,138);
  font-weight: 600;
  white-space: nowrap;
}
.trend-section{
  box-shadow: 0 3px 6px -2px rgba(255, 241, 241, 0.5); 
  border-radius: 0 0 20px 20px;
}
.history-section{
   border-radius: 20px 20px 0 0;
}
@font-face {
  font-family: 'iconfont';
  src: url('iconfont.ttf?t=1749735311523') format('truetype');
}
.iconfont {
  font-family: "iconfont" !important;
  font-size: 31px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
</style>

